<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/model/fields/File.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/utils/DirectoryUtils.php';

include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/database/core/FilenameCollection.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/core/Filename.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/graphics/BitmapDimensions.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/graphics/Bitmap.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/utils/BitmapUtils.php';

include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/database/core/IAutoUpdateColumn.php';

class BitmapFile extends File implements IAutoUpdateColumn
{	
	public $path;
	public $bitmapDimensions;
	public $shouldPrefix;
	public $file_data;
	public $shouldAppendColumnToPath;
	
	protected $filenameMemento;
	
	/**
	 * undocumented function
	 *
	 * @array $fileTypes array of allowed fileTypes
	 * @return ImageFile
	 **/
	
	public function __construct(IDatabaseRecord &$object, BitmapDimensions $bitmapDimensions = null, $path = null, $shouldPrefix = true, $shouldAppendColumnToPath = true, $length = null)
	{
		// previoulsy was using debug_backtrace()
		// but we found an issue when (we think) php was running as CGI.  The ['object']
		// key was not being passed.
		// signature was:
		// public function __construct($length = null, $defaultValue = null)
		// $this->model was being set via:
		// $tmp =  debug_backtrace();
		// $this->model        = &$tmp[1]['object'];

		$config = PhormConfig::getConfig();

		$this->model                    = $object;
		$this->field_type               = "string";
		$this->length                   = ($length) ? $length : 75;
		$this->path                     = $path == null ? $config->mediaPath."/".strtolower(get_class($this->model)) : $path;
		
		$this->bitmapDimensions         = $bitmapDimensions;
		$this->shouldPrefix             = $shouldPrefix;
		$this->filenameMemento          = new FilenameCollection();
		$this->file_data                = $file_data;
		$this->shouldAppendColumnToPath = $shouldAppendColumnToPath;
		$this->context                  =& $_FILES;
	}
	
	public function update()
	{
		if(!$this->file_data)
			$this->file_data = &$this->column;
		
		if ($this->shouldAppendColumnToPath)
		{
			if (!strpos($this->path, $this->column))
				$this->path = $this->path.'/'.$this->column;
		}
		
		DirectoryUtils::createDirectoryChain($this->path);
		
		if (!$this->context[$this->file_data]['error'] && $this->isDirty)
		{
			if ($this->data['value'])
			{
				if ($this->model->isNew)
				{
					if ($this->bitmapDimensions)
					{
						$filenameWithPath = $_SERVER['DOCUMENT_ROOT']."/".$this->path."/".$this->data['value'];

						$file = Bitmap::initWithFile($this->context[$this->file_data]['tmp_name']);
						$file = $file->resize($this->bitmapDimensions);
						$file->save($filenameWithPath);
					}
					else
					{	
						FileUtils::updateFile($this->context[$this->file_data], $this->path."/".$this->data['value']);
					}
				}
				else
				{
					if ($this->data['value'])
					{
						//FileUtils::delete($this->path.'/'.$this->data['value']);
						foreach($this->filenameMemento as $filename)
						{
							FileUtils::delete($this->path.'/'.$filename);
						}
					}
					if ($this->bitmapDimensions)
					{
						$filenameWithPath = $_SERVER['DOCUMENT_ROOT']."/".$this->path."/".$this->data['value'];

						$file = Bitmap::initWithFile($this->context[$this->file_data]['tmp_name']);
						$file = $file->resize($this->bitmapDimensions);
						$file->save($filenameWithPath);
					}
					else
					{	
						FileUtils::updateFile($this->context[$this->file_data], $this->path."/".$this->data['value']);
					}
				}
			}
			else
			{
				foreach($this->context as $fileData)
				{		
					// this is going to assume that we will NOT be uploading multiple files with the same filename
				
					if ($fileData['name'] == $this->data['value'] || $fileData['name'] == substr($this->data['value'], 7))
					{
						if ($this->model->isNew)
						{
							if ($this->bitmapDimensions)
							{
								$filenameWithPath = $_SERVER['DOCUMENT_ROOT']."/".$this->path."/".$this->data['value'];

								$file = Bitmap::initWithFile($this->context[$this->file_data]['tmp_name']);
								$file = $file->resize($this->bitmapDimensions);
								$file->save($filenameWithPath);
							}
							else
							{	
								FileUtils::updateFile($fileData, $this->path."/".$this->data['value']);
							}
						}
						else
						{
							if ($this->data['value'])
							{
								//FileUtils::delete($this->path.'/'.$this->data['value']);
								foreach($this->filenameMemento as $filename)
								{
									FileUtils::delete($this->path.'/'.$filename);
								}
							}	
						
							if ($this->bitmapDimensions)
							{
								$filenameWithPath = $_SERVER['DOCUMENT_ROOT']."/".$this->path."/".$this->data['value'];

								$file = Bitmap::initWithFile($this->context[$this->file_data]['tmp_name']);
								$file = $file->resize($this->bitmapDimensions);
								$file->save($filenameWithPath);
							}
							else
							{	
								FileUtils::updateFile($fileData, $this->path."/".$this->data['value']);
							}
						}
					}
				}
			}
		}
		else if ($this->filenameMemento->length)
		{
			foreach($this->filenameMemento as $filename)
			{
				FileUtils::delete($this->path.'/'.$filename);
			}
		}
	}
}
?>
